#!/usr/bin/env python3
# vim:fileencoding=utf-8

'''
列出脚本的说明，目前支持 shell 脚本和 python 程序

2010年9月2日
'''

MAXLINE = 10

import sys
argv = sys.argv

def readpy(py, f):
  doc = []
  count = 0
  for l in f:
    count +=1
    if l.startswith("'''") or l.startswith('"""'):
      found = True
      break
    if count > MAXLINE:
      found = False
      break
  if found:
    l = l.lstrip(''''"''').rstrip()
    if l:
      doc.append(l)
    while True:
      if l.endswith('"""') or l.endswith("'''"):
        del doc[-1]
        l = l.rstrip(''''"''')
        if l:
          doc.append(l)
        break
      l = f.readline().rstrip()
      doc.append(l)
    print('\n'.join(doc))
  else:
    print('No doc found.')
  print()

def readsh(sh, f):
  doc = []
  count = 0
  while count < MAXLINE:
    l = f.readline().rstrip()
    count += 1
    if l.startswith('#'):
      doc.append(l.lstrip('# '))
    elif not l.strip():
      continue
    else:
      break
  else:
    print('No doc found.\n')
    return
  print('\n'.join(doc))
  print()

def readfile(file):
  print('\x1b[1;33m', file+':', '\x1b[m\n', sep='')
  try:
    f = open(file)
    l = f.readline()
    if not l.startswith('#!'):
      print('No shebang found.\n')
      return
    if l.find('python') != -1:
      readpy(file, f)
    elif l.find('bash') or l.find('/sh') or l.find('zsh'):
      readsh(file, f)
    else:
      print('Unrecognized file type.\n')
  except UnicodeDecodeError:
    print('Binary file?\n')

if __name__ == '__main__':
  if len(argv) == 1:
    print('No file specified.', file=sys.stderr)
    sys.exit(1)
  for f in argv[1:]:
    readfile(f)

